package com.read.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.alibaba.fastjson.JSONArray;

@WebServlet(urlPatterns = { "/upload" })
@MultipartConfig
public class IndexServlet extends HttpServlet{

	private String getFileName(Part part){
		String content = part.getHeader("content-disposition");
		
		String [] elements = content.split(";");
		for(String element : elements){
			if(element.trim().startsWith("filename")){
				 String s = element.substring(element.indexOf('=') +1).trim().replace("\"", "");
				 return s.substring(s.lastIndexOf('\\')+1).trim();
			}
		}
		return null;
	}
	
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		Part part = req.getPart("file");
		String fileName = getFileName(part);
		if(fileName != null && !fileName.isEmpty()){
			part.write(getServletContext().getRealPath("/upload")+"\\"+fileName);
		}
		
		PrintWriter writer = resp.getWriter();
		Map<String, String> map = new HashMap<String, String>();
		map.put("flag", "sucess");
		String json = JSONArray.toJSONString(map);
		writer.write(json);
		writer.close();
	}
	
	
}
